from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List, Optional

from config.get_db import get_db
from module_admin.entity.vo.user_vo import CurrentUserModel
from module_admin.service.login_service import LoginService
from module_user.service.bg_user_affiliate_service import BgUserAffiliateService
from module_user.entity.vo.bg_user_affiliate_vo import BgUserAffiliateModel, AffiliateStatsModel
from utils.response_util import ResponseUtil
from utils.string_util import StringUtil

router = APIRouter(prefix="/bg/affiliate", tags=["推广返利管理"])

affiliate_service = BgUserAffiliateService()


@router.get("/list", summary="获取推广返利列表")
async def get_affiliate_list(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(20, ge=1, le=100, description="每页数量"),
    email: Optional[str] = Query(None, description="用户邮箱"),
    affiliate_code: Optional[str] = Query(None, description="推广码"),
    status: Optional[int] = Query(None, description="状态"),
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user),
):
    """获取推广返利列表（管理端）"""
        # 这里需要实现管理端的查询逻辑
        # 暂时返回空列表，实际应该查询所有用户的推广信息
    result = await affiliate_service.get_admin_affiliate_list(
        db, page, size, email, affiliate_code, status
    )
    return ResponseUtil.success(data=result)


@router.get("/detail/{user_id}", summary="获取推广详情")
async def get_affiliate_detail(
    user_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user),
):
    """获取指定用户的推广详情"""
        # 获取推广信息
    affiliate_info = await affiliate_service.get_affiliate_info(db, user_id)
    if not affiliate_info:
        raise HTTPException(status_code=404, detail="推广信息不存在")


    # 获取统计信息
    stats = await affiliate_service.get_affiliate_stats(db, user_id)

    # 获取被邀请人列表
    invitee_list = await affiliate_service.get_invitee_list(db, user_id, 1, 100)

    # 获取返利记录
    commission_list = await affiliate_service.get_commission_records(db, user_id, 1, 100)

    result = {
        "user_id": user_id,
        "affiliate_info": affiliate_info,
        "stats": stats,
        "invitee_list": invitee_list,
        "commission_list": commission_list
    }

    return ResponseUtil.success(data=result)


@router.put("/status/{user_id}", summary="更新推广状态")
async def update_affiliate_status(
    user_id: int,
    status: int,
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user),
):
    """更新用户的推广状态"""
    result = await affiliate_service.update_affiliate_status(db, user_id, status)
    return ResponseUtil.success(data=result)


@router.put("/commission/settle/{commission_id}", summary="结算返利")
async def settle_commission(
    commission_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user),
):
    """结算指定返利记录"""
    result = await affiliate_service.settle_commission(db, commission_id)
    return ResponseUtil.success(data=result)


@router.put("/commission/cancel/{commission_id}", summary="取消返利")
async def cancel_commission(
    commission_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user),
):
    """取消指定返利记录"""
    result = await affiliate_service.cancel_commission(db, commission_id)
    return ResponseUtil.success(data=result)


@router.put("/commission/batch-settle/{user_id}", summary="批量结算返利")
async def batch_settle_commission(
    user_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user),
):
    """批量结算指定用户的所有待结算返利"""
    result = await affiliate_service.batch_settle_commission(db, user_id)
    return ResponseUtil.success(data=result)


@router.put("/ali-pay-info/{user_id}", summary="更新支付宝信息")
async def update_ali_pay_info(
    user_id: int,
    ali_pay_account: Optional[str] = None,
    ali_pay_name: Optional[str] = None,
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user),
):
    """更新用户的支付宝信息"""
    result = await affiliate_service.update_ali_pay_info(db, user_id, ali_pay_account, ali_pay_name)
    return ResponseUtil.success(data=result)
